_package("caf.core");

/**
 * 图片文件缓存
 */
_class("FileCache", "", function(){
	var no_thumbPath = null;
	this._init = function(){
		_super._init.call(this);
		this._app = null;
		this._version = 0;
	};
	this.create = function(app){
		this._app = app;
	};
	this.dispose = function(){
		this._app = null;
		_super.dispose.apply(this);
	};
	this.testWrite = function(){
		try{
			CloudAPI.File.write("test content", "test.file", "true");  //覆盖文件内容
			this._version = 2;
			return true;
		}catch(ex){
			try{
				CloudAPI.File.write("test content", "test.file");
				this._version = 1;
				return true;
			}catch(ex){
				runtime.log("--------");
				runtime.log(ex);
				return false;
			}
		}
	};
	/**
	 * [TODO]需要缓存请求的数据
	 * [TODO]使用localStorage模拟本地文件读写接口
	 */
	this.writeFile = function(file, content){
		try{  //如果write接口还不支持，可能会报错
			if(this._version == 2){
				return CloudAPI.File.write(content, file, "true");  //覆盖文件内容
			}else if(this._version == 1){
				return CloudAPI.File.write(content, file);
			}
		}catch(ex){
			return "";
		}
	};
	/**
	 * 保存图片的base64编码内容到sdcard
	 */
	this.cache = function(filename, url, params, agent, func){
		this._app.netInvoke("GET", url, params, "base64", this, function(json){
			var path = this.writeFile(filename, "data:" + json.mimetype + ";base64," + json.data);
			func.apply(agent, [path]);
		});
	};
	this.cache1 = function(filename, url, params, agent, func){
		if(filename == "images-no_thumb.png"){
			if(no_thumbPath === null){
				no_thumbPath = "";
				this.cache(filename, url, params, this, function(path){
					no_thumbPath = path;
					func.apply(agent, [path]);
				});
			}else{
				runtime.startTimer(15, this, function(){
					if(no_thumbPath != ""){
						func.apply(agent, [no_thumbPath]);
					}else{
						return true;
					}
				});
			}
		}else{
			this.cache(filename, url, params, this, function(path){
				func.apply(agent, [path]);
			});
		}
	};
});